package models

import (
	"encoding/json"
	"fmt"
	"sync"
)

var (
	ItemCache map[int]*Item
	lock      sync.RWMutex
)

func CacheSetItem(item *Item) {
	lock.Lock()
	defer lock.Unlock()
	ItemCache[item.Id] = item

}

func GetItemByUserid(Id int) string {

	var res []*Item
	for _, item := range ItemCache {
		if item.SallerId == Id {
			res = append(res, item)
		}
	}

	str := "[]"
	if res != nil {
		b, err := json.Marshal(res)
		if err != nil {
			fmt.Println(err.Error())
		} else {
			str = string(b)
		}
	}
	return str
}

func GetItem(id int) *Item {
	if item, exist := ItemCache[id]; exist {
		return item
	} else {
		return nil
	}
}

func init() {
	ItemCache = make(map[int]*Item)
}
